
package com.updesignsz.admin.controller;

import com.updesignsz.admin.service.ArticleService;
import com.updesignsz.admin.util.ResponseUtil;
import com.updesignsz.admin.vo.form.ArticleForm;
import com.updesignsz.commom.entity.Article;
import com.updesignsz.commom.util.DateUtil;
import com.updesignsz.commom.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 文章
 * Creation date 2020-8-8 15:06:04
 */
@RestController

public class ArticleController {

	@Autowired
	private ArticleService articleService;
	/**
	 * 文章列表
	 */
	@GetMapping("/article")
	public void insuranceArticle(Article article, HttpServletResponse response) {
		ResultVo vo = new ResultVo();
		vo.setData(articleService.listAll(article));
		ResponseUtil.outJson(vo.toJsonMsg(), response);
	}

	/**
	 * 保存 文章
	 */
	@PostMapping("/article")
	public void addArticle(@Validated(PostMapping.class) @RequestBody ArticleForm form, HttpServletResponse response) {
		ResultVo vo = new ResultVo();
		Article article = convert(form);
		List<Article> list = articleService.listAll(article);
		if (list.size() == 0 || form.getType() == 2) {
			articleService.saveArticle(article);
			vo.setData(articleService.getById(article.getId()));
		} else {
			vo.setResultVo(1, "该类型文章已存在，只能添加一条记录！");
		}
		ResponseUtil.outJson(vo.toJsonMsg(), response);
	}


	/**
	 * 删除 文章
	 */
	@DeleteMapping("/article/{articleId}")
	public void deleteArticle(@PathVariable Integer articleId, HttpServletResponse response) {
		ResultVo vo = new ResultVo();
		articleService.deleteArticle(articleId);
		ResponseUtil.outJson(vo.toJsonMsg(), response);
	}

	/**
	 * 修改 文章
	 */
	@PutMapping("/article")
	public void updateArticle(@Validated(PutMapping.class) @RequestBody ArticleForm form, HttpServletResponse response) {
		ResultVo vo = new ResultVo();
		Article article = convert(form);
		articleService.updateArticle(article);
		vo.setData(articleService.getById(article.getId()));
		ResponseUtil.outJson(vo.toJsonMsg(), response);
	}


	private Article convert(ArticleForm articleForm) {
		Article article = new Article();
		article.setId(articleForm.getId());
		article.setTitle(articleForm.getTitle());
		article.setContent(articleForm.getContent());
		article.setType(articleForm.getType());
		article.setCover(articleForm.getCover());
		String[] images = articleForm.getCover().split(",");
		if (images.length > 0) {
			article.setCoverThumbnail(images[0].replace("uploads/", "uploads/thumb_"));
		}
		return article;
	}
}